/**
 * mongoodb 数据库链接
 */
import config from '../../config/app';
import Mongoose from "mongoose";

let mongodbConfig = config.mongodb || {};
let uri:string = '';
if (mongodbConfig.uri && mongodbConfig.uri !== '') {
    uri = mongodbConfig.uri;
} else {
    uri = `mongodb://${mongodbConfig.user}:${mongodbConfig.pass}@${mongodbConfig.host}:${mongodbConfig.port}/${mongodbConfig.database}`;
}

Mongoose.Promise = global.Promise;

const options = {
    useNewUrlParser: true,
    autoIndex: false, // Don't build indexes
    reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
    reconnectInterval: 500, // Reconnect every 500ms
    poolSize: 10, // Maintain up to 10 socket connections
    // If not connected, return errors immediately rather than waiting for reconnect
    bufferMaxEntries: 0
};

export default async () => {
    try {
        let connection = await Mongoose.connect(uri, options);
        console.info('[✔️]数据库链接成功 \n\r')
    } catch (error) {
        console.error("[✘]mongodb 数据库连接失败");
    }
    return Mongoose;
}